<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-02-15 22:52:42
 * Desc:
 */

namespace app\base\service\WeChat;

use app\base\service\BaseService;
use EasyWeChat\Factory;
use app\core\storage\COS;
use app\base\model\miniProgram\MiniProgramScene;
use app\core\cache\{RedisCache, RedisKeys};
use app\core\exception\{BusinessException, ErrorCode};
use app\core\log\Log4dd;

class MiniProgramQrCodeService extends BaseService
{

    const SAVE_PATH = TEMP_PATH . '/mini_qrcode';

    public function __construct()
    {
        RedisCache::selectDB(config('redis_db_index.wx'));
    }

    public static function getUnLimitMiniQrCode($path, $params, $options = [], $app_id = '')
    {


        try {
            $config = WeChatBaseService::getConfigByAppId($app_id, 'mini_program');
            $app = Factory::miniProgram($config);

            $key = md5(implode('', array_values($params)));
            $scene = md5($key);
            // 保存scene
            self::updateMiniSceneData($scene, [
                'scene' => $scene,
                'app_id' => $config['app_id'],
                'user_id' => $params['user_id'] ?? '',
                'path_page' => $path,
                'content' => json_encode($params),
            ]);

            $response = $app->app_code->getUnlimit($scene, [
                //'page' => $path,
                'width' => $options['width'] ?? 430,
                //Int - 默认 430 二维码的宽度
                'auto_color' => $options['auto_color '] ?? false,
                //默认 false 自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
                'line_color' => $options['line_color '] ?? [],
                //auto_color 为 false 时生效，使用 rgb 设置颜色 例如 ，示例：["r" => 0,"g" => 0,"b" => 0]
                'is_hyaline' => $options['is_hyaline '] ?? false
                //是否需要透明底色，为 true 时，生成透明底色的小程序
            ]);

            //Log4dd::info("生成小程序二维码返回数据", $response);
            // $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例，失败为数组或你指定的 API 返回类型
            // 保存小程序码到文件
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $response->saveAs(self::SAVE_PATH, $scene . '.png');
                $local_path = self::SAVE_PATH . '/' . $scene . '.png';
                $cosData = Cos::putObject($scene . '.png', $local_path, 'mini_qrcode');
                @unlink($local_path);
                if ($cosData && $cosData['cos_url']) {
                    return $cosData['cos_url'];
                }
            }

            return '';
        } catch (BusinessException $e) {
            Log4dd::info("生成小程序二维码失败:{$e->getMessage()}", func_get_args(), $e);
            return '';
        }
    }

    public static function updateMiniSceneData($scene, $info)
    {
        $data = MiniProgramScene::getDataByScene($scene);
        if (empty($data)) {
            return MiniProgramScene::addData($info);
        } else {
            return MiniProgramScene::updateData($scene, $info);
        }
    }

    public static function getSceneContent($scene)
    {
        if (empty($scene)) {
            Log4dd::info("scene参数未空");
            return [];
        }
        // 查询缓存中是否存在
        $cacheKey = RedisKeys::getMiniProgramSceneKey($scene);
        // 缓存中存在，直接返回
        $cacheData = RedisCache::get($cacheKey);
        if (!empty($cacheData)) {
            return json_decode($cacheData, true);
        }
        // 缓存中不存在，先查询结果，再填充进缓存，然后返回
        $scene_info = MiniProgramScene::where('scene', $scene)->field('content,path_page,app_id')->find();
        if (empty($scene_info['content'])) {
            Log4dd::info("场景值『{$scene}』不存在");
            return [];
        }
        $content = json_decode($scene_info['content'], true);
        $params = [
            'app_id' => $scene_info['app_id'], // APP_ID
            'page' => $scene_info['path_page'], // 小程序页面
            'content' => $content, // 保存的参数
        ];
        RedisCache::set($cacheKey, json_encode($params), 3600); // 缓存一个小时

        return $params;
    }

}